package com.kaifamiao.xml.d0930;

import com.kaifamiao.xml.d0929.Student;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class Demo {

    public static void main(String[] args) {
        SAXReader reader = new SAXReader();

        InputStream inputStream = Demo.class.getClassLoader().getResourceAsStream("stu.xml");
        try {
            Document document = reader.read(inputStream);

            Element root = document.getRootElement();

            Element students = root.element("students");

            List<Element> list = students.elements("student");
            List<Student> studentList = new ArrayList<>();

            for (Element studentElement : list){
                Element id = studentElement.element("id");
                Element name = studentElement.element("name");
                String nick = name.attributeValue("nick");
                Element gender = studentElement.element("gender");
                Element age = studentElement.element("age");

                Student stu = new Student();

                stu.setId(Integer.parseInt(id.getTextTrim()));
                stu.setName(name.getTextTrim());
                stu.setNick(nick);
                stu.setGender(gender.getTextTrim());
                stu.setAge(Integer.parseInt(age.getTextTrim()));

                studentList.add(stu);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
